$(function () {
    var today;//今天日期
    // 查询常量
    var departureCity;//出发城市
    var arrivalCity;//到达城市
    var datetimepicker;//日期
    var num;//人数
    var flightnum;//航班号
    var passengerName;//姓名
    var passengerID;//身份证号
    var price;//购买价格
    var fid;//航班主键号
    var classType;//预定仓位
    var ID;//当前登录人身份证号
    function get_date() {
        //创建一个当前日期对象
        var now = new Date();
        //格式化日，如果小于9，前面补0
        var day = ("0" + now.getDate()).slice(-2);
        //格式化月，如果小于9，前面补0
        var month = ("0" + (now.getMonth() + 1)).slice(-2);
        //拼装完整日期格式
        today = now.getFullYear() + "-" + (month) + "-" + (day);
        //完成赋值
        $("#datetimepicker1").val(today);
        $("#datetimepicker3").val(today);
    }
    function login() {
        $.ajax({
            type: 'get',//请求方式
            url: 'http://localhost/users',
            contentType: "application/json",
            headers: {

                'Authorization': 'Bearer ' + localStorage.getItem("userToken")
            },
            success: function (res) {

                if (res.code == 200) 
                {
                    $('#login').text(res.data.user['name'] + "/退出登录");
                    ID = res.data.user['identityNumber'];
                }
            }
        })

    }
    // 登陆检查
    login();
    get_date();
    // 获取token
    console.log(localStorage.getItem('userToken'));
    //    登录按钮事件
    $("#login").on("click", function () {
        $('#login,#register').hide();  //登录注册按钮隐藏
        $('#user').show();
        localStorage.setItem('userToken', "");
    });


    // 导航栏主页按钮
    $("#nav1").on("click", function () {
        $('#orderInformation').hide();//订单界面隐藏
        $('#airTicket').hide();//个人行程隐藏
        $('#reserve').show();//主页显示
    });
    //导航栏订单按钮
    $("#nav2").on("click", function () {
        $('#reserve').hide();//主页隐藏
        $('#airTicket').hide();//个人行程隐藏
        $('#orderInformation').show();//订单界面显示
        // 获取订单
        $.ajax({
            type: 'get',//请求方式
            url: 'http://localhost/orders',
            contentType: "application/json",
            headers: {

                'Authorization': 'Bearer ' + localStorage.getItem("userToken")
            },
            success: function (res) {

                if (res.code != 200) return alert('未登录！');
                else {
                    var string = "";
                    for (var i = 0; i < res.data.list.length; i++) {
                        string += '<tr><td>' +
                            res.data.list[i]['createTime'] + '</td><td>' +
                            res.data.list[i]['flightNum'] + '</td><td>' +
                            res.data.list[i]['departureTime'] + '</td><td>' +
                            res.data.list[i]['name'] + '</td><td>' +
                            res.data.list[i]['classType'] + '</td><td>' +
                            res.data.list[i]['price'] + '</td><td>' + '<input type="button" class="btn btn-danger delButton" value="退票" flightid="' +
                            res.data.list[i]['oid'] + '"></td></tr>';
                    }
                    var $tr = $(string);
                    //把创建出来的$tr追加到tbody中去.
                    $('#orderTable').empty().append($tr);
                }
            }
        })
    });
    //导航栏个人行程按钮
    $("#nav3").on("click", function () {
        $('#orderInformation').hide();//订单界面隐藏
        $('#reserve').hide();//主页隐藏
        $('#airTicket').show();//个人行程显示
        // 获取订单
        $.ajax({
            type: 'get',//请求方式
            url: 'http://localhost/orders/' + ID,
            contentType: "application/json",
            headers: {

                'Authorization': 'Bearer ' + localStorage.getItem("userToken")
            },
            success: function (res) {

                if (res.code != 200) return alert('未登录！'); 
                else {
                    var string = "";
                    for (var i = 0; i < res.data.list.length; i++) {
                        string += '<tr><td>' +
                            res.data.list[i]['flightNum'] + '</td><td>' +
                            res.data.list[i]['departureTime'] + '</td><td>' +
                            res.data.list[i]['departure'] + '</td><td>' +
                            res.data.list[i]['classType'] + '</td><td>' +
                            '<input type="button" class="btn btn-danger delButton" value="退票" flightid="' +
                            res.data.list[i]['oid'] + '"></td></tr>';
                    }
                    var $tr = $(string);
                    //把创建出来的$tr追加到tbody中去.
                    $('#ticketInformation').empty().append($tr);
                }
            }
        })
    });
    // 目的地出发地交换
    $("#exchange1").on("click", function () {
        departureCity = $('#departureCity1').val().trim();//出发城市
        arrivalCity = $('#arrivalCity1').val().trim();//到达城市
        $('#departureCity1').val(arrivalCity);
        $('#arrivalCity1').val(departureCity)
    })
    $("#exchange2").on("click", function () {
        departureCity = $('#departureCity2').val().trim();//出发城市
        arrivalCity = $('#arrivalCity2').val().trim();//到达城市
        $('#departureCity2').val(arrivalCity);
        $('#arrivalCity2').val(departureCity)
    })
    //  订单查询界面的查询按钮
    $("#queryButton1").on("click", function () {
        // 获取输入框的值
        departureCity = $('#departureCity1').val().trim();//出发城市
        if (departureCity == "") {
            alert("请输入出发地")
            return;
        }
        arrivalCity = $('#arrivalCity1').val().trim();//到达城市
        if (arrivalCity == "") {
            alert("请输入到达地")
            return;
        }
        datetimepicker = $('#datetimepicker1').val();//日期
        if (datetimepicker < today) {
            alert("请选择正确的日期")
            return;
        }
        var date = new Date(datetimepicker.replace(/-/g, "/")).getTime();//时间戳
        // 结果界面查询输入框默认值
        $('#departureCity2').val(departureCity);//出发城市
        $('#arrivalCity2').val(arrivalCity);//到达城市
        $('#datetimepicker2').val(datetimepicker);//日期
        // 测试输出
        console.log(departureCity);
        console.log(arrivalCity);
        console.log(num);
        console.log(typeof datetimepicker);
        console.log(datetimepicker);
        console.log(date);
        console.log(typeof date);
        // 显示结果
        $('#check').hide();//查询界面隐藏
        $('#flightBooking').show();//查询结果显示
        // 获取查询订单
        $.get('http://localhost/flights?=&departure=' + departureCity + '&destination=' + arrivalCity + '&departureDate=' + datetimepicker + " 00:00:00", function (res) {
            // 判断是否获取成功     

            if (!res.success) return alert('获取预订信息失败');
            var string = "";
            console.log(res.data.list.length);
            for (var i = 0; i < res.data.list.length; i++) {
                string = string + '<tr><td><div class="row"><h2 class="col">' +
                    res.data.list[i]['departure'] + '</h2><h4 class="col">' +
                    res.data.list[i]['flightNum'] + '</h4><h2 class="col">' +
                    res.data.list[i]['destination'] + '</h2></div></td><td>' +
                    res.data.list[i]['departureTime'] + '</td><td>' +
                    res.data.list[i]['arrivalTime'] + '</td><td><div class="row">';
                // 商务舱是否有票
                if (!res.data.list[i]['businessClassAvailable'] == 0) {
                    string += '<div class="col"><div class="">商务舱</div><div class="">' +
                        res.data.list[i]['businessClassPrice'] + '</div><button type="button" class=" btn btn-success businessClassButton"id="" flightId="' +
                        res.data.list[i]['fid'] + '">预定</button></div>';
                }
                //经济舱是否有票
                if (!res.data.list[i]['economyClassAvailable'] == 0) {
                    string += '<div class="col"><div class="">经济舱</div><div class="">' +
                        res.data.list[i]['economyClassPrice'] + '</div><button type="button" class=" btn btn-success economyClassButton"id="" flightId="' +
                        res.data.list[i]['fid'] + '">预定</button></div>';
                }
                string += '</div></td></tr>';

            }
            var $tr = $(string);
            //把创建出来的$tr追加到tbody中去.
            $('#flightTable').empty().append($tr);
        })
    });
    // 查询结果页面的查询按钮
    $("#queryButton2").on("click", function () {
        // 表格内容移除
        // 获取输入框内容
        departureCity = $('#departureCity2').val().trim();//出发城市
        if (departureCity == "") {
            alert("请输入出发地")
            return;
        }
        arrivalCity = $('#arrivalCity2').val().trim();//到达城市
        if (arrivalCity == "") {
            alert("请输入到达地")
            return;
        }
        datetimepicker = $('#datetimepicker2').val();//日期
        if (datetimepicker < today) {
            alert("请选择正确的日期")
            return;
        }
        var date = new Date(datetimepicker.replace(/-/g, "/")).getTime();//时间戳
        // 获取查询订单
        $.get('http://localhost/flights?=&departure=' + departureCity + '&destination=' + arrivalCity + '&departureDate=' + datetimepicker + " 00:00:00", function (res) {
            // 判断是否获取成功     

            if (!res.success) return alert('获取预订信息失败');
            var string = "";
            console.log(res.data.list.length);
            for (var i = 0; i < res.data.list.length; i++) {
                string = string + '<tr><td><div class="row"><h2 class="col">' +
                    res.data.list[i]['departure'] + '</h2><h4 class="col">' +
                    res.data.list[i]['flightNum'] + '</h4><h2 class="col">' +
                    res.data.list[i]['destination'] + '</h2></div></td><td>' +
                    res.data.list[i]['departureTime'] + '</td><td>' +
                    res.data.list[i]['arrivalTime'] + '</td><td><div class="row">';
                // 商务舱是否有票
                if (!res.data.list[i]['businessClassAvailable'] == 0) {
                    string += '<div class="col"><div class="">商务舱</div><div class="">' +
                        res.data.list[i]['businessClassPrice'] + '</div><button type="button" class=" btn btn-success businessClassButton"id="" flightid="' +
                        res.data.list[i]['fid'] + '">预定</button></div>';
                }
                //经济舱是否有票
                if (!res.data.list[i]['economyClassAvailable'] == 0) {
                    string += '<div class="col"><div class="">经济舱</div><div class="">' +
                        res.data.list[i]['economyClassPrice'] + '</div><button type="button" class=" btn btn-success economyClassButton"id="" flightid="' +
                        res.data.list[i]['fid'] + '">预定</button></div>';
                }
                string += '</div></td></tr>';

            }
            var $tr = $(string);
            //把创建出来的$tr追加到tbody中去.
            $('#flightTable').empty().append($tr);
        })
    })
    //机票查询按钮
    $("#queryButton3").on("click", function () {
        // 获取航班号
        num = $('#flightNumber').val().trim();
        if (num == "") {
            alert("请输入航班号")
            return;
        }
        // 获取日期
        datetimepicker = $('#datetimepicker3').val();//日期
        var date = new Date(datetimepicker.replace(/-/g, "/"));//时间戳
    })

    // 商务舱预定按钮
    $("#flightTable").on("click", '.businessClassButton', function () {
        // request.setRequestHeader('Authorization','Bearer '+localStorage.getItem(userToken));
        //查看是否登录
        $.ajax({
            type: 'get',//请求方式
            url: 'http://localhost/users',
            contentType: "application/json",
            headers: {

                'Authorization': 'Bearer ' + localStorage.getItem("userToken")
            },
            success: function (res) {

                if (res.code != 200) return alert('未登录！');
                else {

                    $('#flightBooking').hide();//航班界面隐藏
                    $('#payment').show();//支付界面显示
                }
            }
        })
        // 信息显示
        fid = $(this).attr('flightid');
        $.get('http://localhost/flights/' + fid, function (res) {
            // 判断是否获取成功     

            if (!res.success) return alert('获取预订信息失败');
            var string = "";
            var string = '<h2 class="col">' +
                res.data.flightInformation['departure'] + '</h2><h4 class="col">' +
                res.data.flightInformation['flightNum'] + '</h4><h2 class="col">' +
                res.data.flightInformation['destination'] + '</h2><div class="col"><h4>出发时间</h4><h5>' +
                res.data.flightInformation['departureTime'] + '</h5></div><div class="col"><h4>到达时间</h4><h5>' +
                res.data.flightInformation['arrivalTime'] + '</h5></div><div class="col"><h4>价格</h4><h5>' +
                res.data.flightInformation['businessClassPrice'] + '</h5></div>';
            // 价格记录
            price = res.data.flightInformation['businessClassPrice'];
            classType = "商务舱";
            var $tr = $(string);
            //把创建出来的$tr追加到tbody中去.
            $('#buyFlight').empty().append($tr);
        })
    })
    // 经济舱预订按钮
    $("#flightTable").on("click", '.economyClassButton', function () {
        //查看是否登录
        $.ajax({
            type: 'get',//请求方式
            url: 'http://localhost/users',
            contentType: "application/json",
            headers: {

                'Authorization': 'Bearer ' + localStorage.getItem("userToken")
            },
            //Authorization:'Bearer '+localStorage.getItem("userToken"),
            success: function (res) {

                if (res.code != 200) return alert('未登录！');
                else {

                    $('#flightBooking').hide();//航班界面隐藏
                    $('#payment').show();//支付界面显示
                }
            }
        })

        // 信息显示
        fid = $(this).attr('flightid');
        $.get('http://localhost/flights/' + fid, function (res) {
            // 判断是否获取成功     

            if (!res.success) return alert('获取预订信息失败');
            var string = "";
            var string = '<h2 class="col">' +
                res.data.flightInformation['departure'] + '</h2><h4 class="col">' +
                res.data.flightInformation['flightNum'] + '</h4><h2 class="col">' +
                res.data.flightInformation['destination'] + '</h2><div class="col"><h4>出发时间</h4><h5>' +
                res.data.flightInformation['departureTime'] + '</h5></div><div class="col"><h4>到达时间</h4><h5>' +
                res.data.flightInformation['arrivalTime'] + '</h5></div><div class="col"><h4>价格</h4><h5>' +
                res.data.flightInformation['economyClassPrice'] + '</h5></div>';
            // 价格记录
            price = res.data.flightInformation['economyClassPrice'];
            var $tr = $(string);
            classType = "经济舱";
            //把创建出来的$tr追加到tbody中去.
            $('#buyFlight').empty().append($tr);
        })

    })
    //  支付界面返回按钮
    $("#exitButton").on("click", function () {
        $('#flightBooking').show();//支付界面显示
        $('#payment').hide();//航班界面隐藏
    })
    //  支付界面支付按钮
    $("#reserveButton").on("click", function () {
        passengerName = $('#passengerName').val().trim();
        if (passengerName == "") {
            alert("请输入姓名")
            return;
        }
        passengerID = $('#passengerID').val().trim();
        if (passengerID == "") {
            alert("请输入身份证号")
            return;
        }
        // 预定
        $.ajax({
            type: 'post',//请求方式
            url: 'http://localhost/orders',
            contentType: "application/json",
            headers: {

                'Authorization': 'Bearer ' + localStorage.getItem("userToken")
            },
            data: JSON.stringify({
                "fid": fid,
                "classType": classType,
                "name": passengerName,
                "identityNumber": passengerID,
                "price": price
            }),
            contentType: "application/json",
            success: function (res) {

                if (res.code != 200) return alert('预定失败');
                else {
                    alert("预定成功！！！");
                    $('#payment').hide();//支付界面隐藏
                    $('#check').show();//航班界面显示
                }
            }
        })
    })
    // 退票按钮
    $("#ticketInformation,#orderTable").on("click", '.delButton', function () {
        fid = $(this).attr('flightid');
        $.ajax({
            type: 'delete',//请求方式
            url: 'http://localhost/orders/' + fid,
            contentType: "application/json",
            headers: {

                'Authorization': 'Bearer ' + localStorage.getItem("userToken")
            },
            success: function (res) {
                if (res.code != 200) return alert('退票失败');
                else alert('退票成功！！！');

                  $('#orderInformation').hide();//订单界面隐藏
                 $('#airTicket').hide();//个人行程隐藏
                $('#reserve').show();//主页显示
            }
        })
    })
    // 页面刷新、关闭都会触发该事件
    // $(window).bind('unload', function(){
    //     console.log('unload');//页面刷新、关闭都会触发该事件
    //     localStorage.setItem('userToken', "");
    // });
});